package cn.chinaunicom.sdsi.upfc_demp.dzgh.controller;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.chinaunicom.sdsi.frm.base.BaseController;
import cn.chinaunicom.sdsi.frm.base.util.ExcelUtils;
import cn.chinaunicom.sdsi.upfc_demp.demo.controller.UpfDemoTestController;
import cn.chinaunicom.sdsi.upfc_demp.dzgh.entity.DzghApplyEntity;
import cn.chinaunicom.sdsi.upfc_demp.dzgh.service.DzghApplyService;
import cn.chinaunicom.sdsi.upfc_demp.jyxx.entity.JyXx;
import net.sf.json.JSONObject;
/**
 * @date 2017-5-10
 * @author 杨镇源
 * @desc 电子公函申请
 */
@Controller
@RequestMapping("dzghApplyController")
public class DzghApplyController extends BaseController{
private final Log log = LogFactory.getLog(UpfDemoTestController.class);
    
    @Autowired
    private DzghApplyService dzghApplyService;

    /**
     * 跳转至电子公函申请页面
     */
    @RequestMapping("/dzghApplyControllerMain")
    public ModelAndView dzghApplyControllerMain(ModelAndView mv){
    	log.debug("dzghApplyController.dzghApplyControllerMain{}");
        log.info("跳转到电子公函申请页面");
        DzghApplyEntity bean = this.dzghApplyService.getSessionStaff();
        //获取电子公函编码
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String elec_id = "GHBH"+df.format(new Date())+((int)(Math.random()*900)+100);// new Date()为获取当前系统时间
        bean.setElec_id(elec_id);
        //bean.setProv("山东省");
        //bean.setEparchy_code("济南市");
        // bean.setOrg_id("济南市公安局");
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //bean.setApply_staff_id("123");
        //bean.setJybh("JYBH00001");
        mv.addObject("bean", bean);
        mv.setViewName("dzgh/dzghApply");
        return mv;
    }
    /**
     * 保存数据
     */
    @ResponseBody
    @RequestMapping("/addDzgh")
    public int addDzgh(DzghApplyEntity dzghApplyEntity){
    	log.info("保存电子公函数据");
        SimpleDateFormat  df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dzghApplyEntity.setApply_date(df.format(new Date()));
        dzghApplyEntity.setStatus("0");
        int insertnum = dzghApplyService.addDzgh(dzghApplyEntity);
        return insertnum;
    }
    
    
    /**
     * 跳转至电子公函详情展示页面
     * auth：jingrongze
     */
    @RequestMapping("/dzghCheck")
    public ModelAndView dzghCheck(ModelAndView mv){
        log.debug("dzghApplyController.dzghApplyControllerMain{}");
        DzghApplyEntity bean = new DzghApplyEntity();
        mv.setViewName("frm/dzgh/dzghCheck");
        return mv;
    }
    
    
    /**
     * 查询电子公函基本信息数据
     * auth：jingrongze  
     */
    @ResponseBody
    @RequestMapping("/selectInfo")
    public JSONObject selectInfo(DzghApplyEntity dzghApplyEntity,HttpServletRequest request){
        //取基本信息
        DzghApplyEntity bean=dzghApplyService.selectByPrimaryKey(dzghApplyEntity);
        //取办案人员姓名一个或者多个SEL_STAFF_ID
        String elec_id = bean.getElec_id();
        //查出ID来
        List<DzghApplyEntity> sel_id = dzghApplyService.getBaId(elec_id);
        //查出办案人员name来
        String sumName = "";
        for(int i=0;i<sel_id.size();i++){
            DzghApplyEntity entity = sel_id.get(i);
            String name = dzghApplyService.getNameById(entity.getSel_staff_id());
            name = "<a href='javascript:void(0)' style='color:#337ab7;' onclick='toBanAnXx("+entity.getSel_staff_id()+")' >"+name+"</a>";
            if(!"".equals(sumName) && sumName !=null){
                sumName = sumName +","+ name;
            }else{
                sumName = name;
            }  
        }
        //取申请人员姓名1个
        String applyId = bean.getApply_staff_id();
        String applyName = dzghApplyService.getApplyName(applyId);
        //取核验号码数量
        dzghApplyEntity.setElec_id(elec_id);
        JSONObject obj = new JSONObject();
        int count = dzghApplyService.selectCountByPrimaryKey(dzghApplyEntity);
        obj.element("elec_id", bean.getElec_id());
        obj.element("name", bean.getName());
        obj.element("prov", bean.getProv());
        obj.element("eparchy_code", bean.getEparchy_code());
        obj.element("apply_staff_id", bean.getApply_staff_id());
        obj.element("org_id", bean.getOrg_id());
        obj.element("sel_staff_id", bean.getSel_staff_id());
        obj.element("valid_start_date", bean.getValid_start_date());
        obj.element("valid_end_date", bean.getValid_end_date());
        obj.element("apply_desc", bean.getApply_desc());
        obj.element("apply_date", bean.getApply_date());
        obj.element("num", "共有"+count+"条");
        obj.element("sumName", sumName);
        obj.element("applyName", applyName);
        obj.element("applyId", applyId);
        obj.element("org_name", bean.getOrg_name());
        obj.element("eparchy_code_name", bean.getEparchy_name());
        obj.element("prov_name", bean.getProv_name());
      //增加一个viewType传值，如果是1就是已办必须显示是否收到纸质==放到前台实现
        /*String viewType = request.getParameter("viewType");
        if("1".equals(viewType)){
            //状态是1：显示是否有纸质checkbox并且是选中是
            obj.element("usertask_status", "1");
            obj.element("sf_status", "1");
            
        }else{
            //obj.element("usertask_status", "0");
            ////增加一个属性userTask的值如果是userTask5前台显示是否收到纸质checkbox
            String usertask = request.getParameter("taskDefinitionKey");
            if("usertask5".equals(usertask)){
                //状态是1：是usertask5,显示是否有纸质checkbox
                obj.element("usertask_status", "1");
            }else{
                obj.element("usertask_status", "0");
            }
        }*/
        
        return obj;
    }
    
    /**
     * 核验号码展现页面
     * auth：jingrongze
     */
    @RequestMapping("/hyNumCheck")
    public ModelAndView hyNumCheck(ModelAndView mv){
        log.debug("dzghApplyController.hyNumCheck{}");
        DzghApplyEntity bean = new DzghApplyEntity();
        mv.setViewName("frm/dzgh/hyNumCheck");
        return mv;
    }
    /**
     * 上传附件
     * 
     * */
    @RequestMapping("/uploadAttachment")
    @ResponseBody
    public JSONObject uploadAttachment(DzghApplyEntity dzghApplyEntity) throws Exception{
        log.info("电子公函申请上传附件");
        ExcelUtils excelUtils = new ExcelUtils();
        MultipartFile myfile = dzghApplyEntity.getMyfile();
        String filename = myfile.getOriginalFilename();
        InputStream is = myfile.getInputStream();
        long length = myfile.getSize();
        // 小数据量示例
        List[] result = excelUtils.inputExcel(is, filename, 0, 0, 0);
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> m = new HashMap<String,String>();
        SimpleDateFormat  df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DecimalFormat decf = new DecimalFormat("#");
        String elec_id = dzghApplyEntity.getElec_id();
        String in_date = df.format(new Date());
        for (int i = 0; i < result.length; i++) {
            if (null == result[i]) {//判断是否空行
                continue;
            }
            for (int j = 0; j < result[i].size(); j++) {
                m.put("elec_id", elec_id);
                m.put("num", decf.format(Double.valueOf(result[i].get(j).toString().trim())));
                m.put("in_date",in_date);
                list.add(m);
                m = new HashMap<String,String>();
            }           
        }
        is.close();
        JSONObject obj = new JSONObject();
        if(!list.isEmpty()){
            this.dzghApplyService.delDzghNum(elec_id);//先删除，后新增
            this.dzghApplyService.addDzghNum(list);
            obj.put("msg", "文件上传成功,共上传"+list.size()+"条。"); 
        }
        else
            obj.put("msg", "文件为空");
        obj.put("oldname", filename);
        obj.put("path", false);
        obj.put("size", (length/1024));
        obj.put("length", length);
        return obj; 
    }
    /**
     * 删除文件信息
     * */
    @RequestMapping("/delAttachment")
    @ResponseBody
    public boolean delAttachment(String elec_id, HttpServletRequest request){
        log.info("删除电子公函号码信息");
       int i=  this.dzghApplyService.delDzghNum(elec_id);
       if(i>=0)
           return true;
       else
           return false;
    }
    /**
     * 通过唯一标示查询单条数据
     * @param entity
     * @param mv
     * @return
     */
    @RequestMapping("/queryByPrimaryKey")
    @ResponseBody
    public ModelAndView queryByPrimaryKey(DzghApplyEntity entity,ModelAndView mv){
        log.info("跳转到电子公函修改页面");
        entity.setElec_id("GHBH20170518164429108");
        DzghApplyEntity bean = this.dzghApplyService.queryByPrimaryKey(entity);
        if(!"".equals(bean.getNum()))
            bean.setNum(bean.getNum().replace(",", ";"));
        //bean.setJybh("JYBH00001");
        mv.addObject("bean",bean);
        mv.setViewName("frm/dzgh/dzghUpdate");
        return mv;
    }
    /**
     * 更新电子公函信息
     * @param dzghApplyEntity
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateDzgh")
    public int updateDzgh(DzghApplyEntity dzghApplyEntity){
        log.info("更新电子公函信息");
        return this.dzghApplyService.updateDzgh(dzghApplyEntity);
        
    }
    public static void main(String[] args) {
        String s = "1,2";
        System.out.println(s.replace(",", ";"));
    }
}
